from flask import (
    Blueprint,
    render_template,
    request,
    session,
    redirect,
    url_for,
    g,
    jsonify
)
from .forms import (
    LoginForm, ResetPwdForm,
    BlockadeForm, UnblockForm,
    TradeForm, UpdateAccountForm,
    AddPayAccount, UpdateMoneyForm,
    AddMarketForm, UpdateMarket,
)
from .models import *
from apps.cms.decorators import login_need
import config
from exit import db
from apps.api.models import User, UserRecord
from flask_paginate import Pagination, get_page_parameter
from utils import restful, common_util, img_path, api_util, tree
from apps.common.models import *
from apps.mall.models import *
from datetime import datetime, date
import os
import shortuuid
from sqlalchemy import or_, func
from decimal import Decimal
import json


bp = Blueprint("cms", __name__, url_prefix="/cms")


@bp.route('/cms_upload/', methods=['GET', 'POST'])  # 上传图片接口
@login_need
def cms_upload():

    file = request.files['file']
    if file:
        time_path = datetime.today().strftime('%Y%m%d')
        file_path = os.path.join('static/images/' + time_path)
        # file_path = os.path.join('/home/nginx/assets1/images/bbs/' + time_path)
        if not os.path.exists(file_path):
            os.mkdir(file_path)

        uuid = shortuuid.uuid()
        dir_path = os.path.join('static/images/' + time_path + '/', uuid + '.jpg')
        file.save(dir_path)
        file.close()
        img_paths = img_path() + dir_path
        return restful.success(data={'url': img_paths})
    else:
        return restful.params_error(message='请上传图片')


@bp.route('/login/', methods=['GET', 'POST'])  # 登录
def login():
    if request.method == 'GET':
        return render_template('base/page-login.html')
    else:
        form = LoginForm(request.form)
        if form.validate():
            username = form.username.data
            password = form.password.data
            remember = form.remember.data
            user = CMSUser.query.filter(or_(CMSUser.username == username, CMSUser.telephone == username)).first()
            if user and user.check_password(password):
                if user.error_num > 5:
                    message = '密码输入错误超过5次，账号被锁定'
                    return restful.params_error(message=message)
                user.token = shortuuid.uuid()
                session[config.CMS_USER_ID] = user.token
                if remember:
                    session.permanent = True
                user.error_num = 0
                db.session.commit()
                # print('---------')
                return restful.success()
            else:
                message = '用户名或者密码输入错误'
                if user:
                    if user.error_num > 5:
                        user.token = '用户名或密码连续输入错误锁定'
                        message = '密码输入错误超过5次，账号被锁定'
                        return restful.params_error(message=message)
                    user.error_num += 1
                    db.session.commit()
                return restful.params_error(message=message)
        else:
            message = form.get_error()
            return restful.params_error(message=message)


@bp.route('/login_out/')  # 注销
@login_need
def login_out():
    del session[config.CMS_USER_ID]
    return redirect(url_for('cms.login'))


@bp.route('/reset_pwd/', methods=['GET', 'POST'])  # 修改密码
@login_need
def reset_pwd():
    if request.method == 'GET':
        return render_template('base/reset_pwd.html')
    else:
        form = ResetPwdForm(request.form)
        if form.validate():
            old_pwd = form.old_pwd.data
            new_pwd = form.new_pwd.data
            user = g.cms_user
            if user.check_password(old_pwd):
                user.password = new_pwd
                db.session.commit()
                del session[config.CMS_USER_ID]
                return restful.success()
            else:
                # return jsonify({"code":400,"message":"旧密码输入错误"})
                message = '旧密码输入错误'
                return restful.params_error(message=message)
        else:
            message = form.get_error()
            return restful.params_error(message=message)


@bp.route('/profile/')  # 个人信息
@login_need
def profile():
    return render_template('base/cms-profile.html')
    # return render_template('views/set/user/info.html')


@bp.route('/update_logo/', methods=['POST'])
@login_need
def update_logo():
    logo_big = request.form.get('big_img')
    logo_small = request.form.get('small_img')
    if logo_big == '' or logo_small == '':
        return restful.params_error(message='请上传图片')
    cms_users = CMSUser.query.all()
    for i in cms_users:
        i.logo_big = logo_big
        i.logo_small = logo_small
    db.session.commit()
    return restful.success()


@bp.route('/')
@login_need
def home():
    goods_type = GoodsCategory.query.order_by(GoodsCategory.priority).all()
    return render_template('base/base.html', goods_type=goods_type)


@bp.route('/index/')  # 首页
@login_need
def index():
    return render_template('base/index.html')


@bp.route('/trade_manages/')  # 交易时间
@login_need
def trade_manages():
    trade_time = TradeManage.query.all()
    return render_template('cms/cms_trade_time.html', trade_time=trade_time)


@bp.route('/trade_time_info/')  # 交易时间信息
@login_need
def trade_time_info():
    trade_time = TradeManage.query.all()
    count = TradeManage.query.count()
    trade_list = list()
    for i in trade_time:
        time_info = dict()
        time_info['trade_id'] = i.id
        time_info['trade_name'] = i.trade_name
        time_info['start_time'] = i.start_time.strftime('%H:%M:%S')
        time_info['end_time'] = i.end_time.strftime('%H:%M:%S')
        time_info['trade_status'] = i.trade_status

        trade_list.append(time_info)
    return restful.table_success(data=trade_list, count=count)


@bp.route('/u_trade_time/', methods=['POST'])  # 修改交易时间
@login_need
def u_trade_time():
    form = TradeForm(request.form)
    if form.validate():
        trade_id = form.trade_id.data
        start_time = form.start_time.data
        end_time = form.end_time.data
        trade_time = TradeManage.query.get(trade_id)
        if trade_time is None:
            return restful.params_error(message='没有这条数据')
        trade_time.start_time = start_time
        trade_time.end_time = end_time
        record = '修改 <{}> 交易时间'.format(trade_time.trade_name)
        cms_record = CMSRecord(cms_id=g.cms_user.id, record=record, ip=request.remote_addr)
        db.session.add(cms_record)
        db.session.commit()
        return restful.success()
    else:
        return restful.params_error(message=form.get_error())


@bp.route('/reset_trade/', methods=['POST'])  # 开启，暂停交易
@login_need
def reset_trade():
    trade_id = request.form.get('trade_id')
    status = request.form.get('status')
    if not trade_id:
        return restful.params_error(message=u'请输入id')
    if not status:
        return restful.params_error(message=u'请输入状态')
    trade_time = TradeManage.query.get(trade_id)
    if not trade_time:
        return restful.params_error(message=u'没有这条数据')
    status = int(status)
    if status == 0:
        trade_time.trade_status = 0
        record = '开启 <{}> 交易'.format(trade_time.trade_name)
        cms_record = CMSRecord(cms_id=g.cms_user.id, record=record, ip=request.remote_addr)
        db.session.add(cms_record)
    elif status == 1:
        trade_time.trade_status = 1
        record = '暂停 <{}> 交易'.format(trade_time.trade_name)
        cms_record = CMSRecord(cms_id=g.cms_user.id, record=record, ip=request.remote_addr)
        db.session.add(cms_record)
    db.session.commit()
    return restful.success()


@bp.route('/pay_accounts/')  # 收款账户
@login_need
def pay_accounts():
    pay_account = PayAccount.query.all()
    return render_template('cms/cms_pay_account.html', pay_account=pay_account)


@bp.route('/pay_accounts_info/')  # 收款信息
@login_need
def pay_accounts_info():
    pay_account = PayAccount.query.all()
    count = PayAccount.query.count()
    account_list = list()
    for i in pay_account:
        pay_info = i.pay_account_json()
        if i.pay_type == 0:
            pay_info['pay_type'] = ''
        elif i.pay_type == 2:
            pay_info['pay_type'] = ''
        elif i.pay_type == 3:
            pay_info['pay_type'] = ''
        elif i.pay_type == 6:
            pay_info['pay_type'] = ''
        pay_info['account_id'] = i.id
        account_list.append(pay_info)
    return restful.table_success(data=account_list, count=count)


@bp.route('/u_pay_account/', methods=['POST'])  # 修改收款账户
@login_need
def u_pay_account():
    form = UpdateAccountForm(request.form)
    if form.validate():
        pay_card = form.pay_card.data
        # bank_name = form.bank_name.data
        real_name = form.real_name.data
        pay_img = form.pay_img.data
        pay_name = form.pay_name.data
        account_id = form.account_id.data
        pay_account = PayAccount.query.filter_by(id=account_id).first()
        if pay_account is None:
            return restful.params_error(message='未找到数据')
        # if bank_name == '' or bank_name == '无':
        #     bank_name = None
        if pay_img == '' or pay_img == '无':
            pay_img = None
        pay_account.pay_card = pay_card
        pay_account.pay_img = pay_img
        # pay_account.bank_name = bank_name
        pay_account.real_name = real_name
        pay_account.pay_name = pay_name
        record = '修改 <{}> 付款方式'.format(pay_account.pay_name)
        cms_record = CMSRecord(cms_id=g.cms_user.id, record=record, ip=request.remote_addr)
        db.session.add(cms_record)
        db.session.commit()
        return restful.success()
    else:
        return restful.params_error(message=form.get_error())


@bp.route('/money_manage/')     # 全局参数
@login_need
def money_manage():
    if g.cms_user.permission == 10:
        moneys = GlobalParams.query.all()
    else:
        moneys = GlobalParams.query.filter(GlobalParams.g_type != 3).all()
    return render_template('cms/money_manage.html', moneys=moneys)


@bp.route('/money_manage_info/')     # 全局参数
@login_need
def money_manage_info():
    if g.cms_user.permission == 10:
        moneys = GlobalParams.query.all()
    else:
        moneys = GlobalParams.query.filter(GlobalParams.g_type != 3).all()
    count = GlobalParams.query.count()
    moneys_list = list()
    for i in moneys:
        money_json = dict()
        money_json['money_id'] = i.id
        money_json['global_params'] = i.global_params
        money_json['g_name'] = i.g_name
        moneys_list.append(money_json)

    return restful.table_success(data=moneys_list, count=count)


@bp.route('/update_money_manage/', methods=['POST'])    # 修改全局参数
@login_need
def update_money_manage():
    form = UpdateMoneyForm(request.form)
    if form.validate():
        money_id = form.money_id.data
        price = form.global_params.data
        # trend = form.trend.data
        # proportion = form.proportion.data
        moneys = GlobalParams.query.filter_by(id=money_id).first()
        if moneys is None:
            return restful.params_error(message='未找到数据')
        price = Decimal(price)
        if moneys.g_type == 9:
            # data = {
            #     30: 1.8,
            #     40: 1.6,
            #     50: 1,
            #     60: 0.9,
            #     80: 0.6,
            #     100: 0.5,
            #     120: 0.4,
            #     240: 0.2,
            #     360: 0.1
            # }
            if price == 0:
                return restful.params_error(message='不能等于0')
            # num_add = data[price]
            # moneys.params_add = num_add

        record = '<{}>价格(数量)<{}> 修改为<{}>'.format(moneys.g_name, moneys.global_params, price)
        moneys.global_params = price

        cms_record = CMSRecord(cms_id=g.cms_user.id, record=record, ip=request.remote_addr)
        db.session.add(cms_record)
        db.session.commit()
        return restful.success()
    else:
        return restful.params_error(message=form.get_error())


@bp.route('/menu_info/')
@login_need
def menu_info():
    data_list = list()
    top_menu = CMSMenu.query.all()
    for i in top_menu:
        data_dict = dict()
        data_dict['id'] = i.id
        data_dict['p_id'] = i.p_id
        data_dict['title'] = i.menu_name
        data_list.append(data_dict)

    root_node = tree.find_root_node(data_list)
    common_node = tree.find_common_node(data_list)

    tree_list = tree.build_tree(root_node, common_node)
    return restful.success(data=tree_list)


@bp.route('/cms_admin/')
@login_need
def cms_admin():
    cms_menu = CMSMenu.query.all()
    goods_store = GoodsStore.query.all()
    return render_template('cms/cms_admin.html', goods_store=goods_store, cms_menu=cms_menu)


@bp.route('/admin_info/')
@login_need
def admin_info():
    cms_user_obj = CMSUser.query.order_by(CMSUser.create_time.desc())
    cms_user = cms_user_obj.all()
    total = cms_user_obj.count()
    data_list = list()
    for i in cms_user:
        data_info = i.cms_user_json()
        data_info['cms_id'] = i.id
        data_info['store_id'] = ''
        store = GoodsStore.query.filter_by(id=i.store_id).first()
        if store:
            data_info['store_name'] = store.name
            data_info['store_id'] = store.id
        cms_role = CMSRole.query.filter_by(cms_id=i.id).all()
        perms = ''
        for j in cms_role:
            # print(j.menu_name)
            perms += j.menu_name
            perms += ' '
        data_info['perms'] = perms
        data_list.append(data_info)
    return restful.table_success(data=data_list, count=total)


@bp.route('/update_admin/', methods=['POST'])
@login_need
def update_admin():
    telephone = request.form.get('telephone')
    username = request.form.get('username')
    password = request.form.get('password')
    store_id = request.form.get('store_id')
    menu_list = request.form.get('menu_list')

    # print(menu_list)

    # print(telephone, username, password, store_id)
    if not all([telephone, username, password, store_id, menu_list]):
        return restful.params_error(message='缺少关键参数')
    menu_list = json.loads(menu_list)
    other_phone = CMSUser.query.filter(or_(CMSUser.telephone == telephone, CMSUser.username == username),).first()
    if other_phone:
        return restful.params_error(message='手机号或用户名已被注册')
    create_user = CMSUser(telephone=telephone, username=username, password=password, store_id=store_id, cms_info=username)
    db.session.add(create_user)
    # db.session.commit()

    for i in menu_list:
        menu = CMSMenu.query.filter_by(id=int(i)).first()
        if menu is None:
            continue
        # print(i, '这是-----------')
        cms_role = CMSRole(menu_id=menu.id, cms_id=create_user.id, menu_name=menu.menu_name)
        # print(create_user.id)
        db.session.add(cms_role)
        db.session.commit()
    record = '添加 <{}> 管理员'.format(create_user.telephone)
    cms_record = CMSRecord(cms_id=g.cms_user.id, record=record, ip=request.remote_addr)
    db.session.add(cms_record)
    db.session.commit()
    return restful.success()


@bp.route('/del_admin/', methods=['POST'])    # 删除管理员
@login_need
def del_admin():
    cms_id = request.form.get('cms_id')
    cms_user = CMSUser.query.filter_by(id=cms_id).first()
    if cms_user is None:
        return restful.params_error(message='未找到用户')
    cms_role = CMSRole.query.filter_by(cms_id=cms_user.id).all()
    for i in cms_role:
        db.session.delete(i)
    record = '删除 <{}> 管理员'.format(cms_user.telephone)
    db.session.delete(cms_user)
    cms_record = CMSRecord(cms_id=g.cms_user.id, record=record, ip=request.remote_addr)
    db.session.add(cms_record)
    db.session.commit()
    return restful.success()


@bp.route('/create_menu/')  # 创建后台菜单
def create_menu():
    menu_list = ['修改密码']
    count = 0
    for i in menu_list:
        menu = CMSMenu.query.filter_by(menu_name=i).first()
        if menu is None:
            p_menu = CMSMenu.query.filter_by(menu_name='我的设置').first()
            if p_menu:
                cms_menu = CMSMenu(menu_name=i, p_id=p_menu.id)
                db.session.add(cms_menu)
                count += 1
    db.session.commit()
    return '成功{}条'.format(count)


@bp.route('/create_cms_user_role/')  # 创建后台菜单
def create_cms_user_role():
    count = 0
    menu_list = CMSMenu.query.all()
    cms_user = CMSUser.query.filter_by(telephone='13333333333').first()
    for i in menu_list:
        cms_role = CMSRole.query.filter_by(menu_name=i.menu_name, menu_id=i.id, cms_id=cms_user.id).first()
        if cms_role is None:
            create_role = CMSRole(menu_id=i.id, cms_id=cms_user.id, menu_name=i.menu_name)
            db.session.add(create_role)
            count += 1
    db.session.commit()
    return '成功{}条'.format(count)


@bp.route('/cms_test/')
def cms_test():
    return '测试'
